<template>
  <div class="vocabulary-practice">
    <el-card class="practice-card">
      <template #header>
        <div class="card-header">
          <span>词汇练习</span>
          <div class="header-info">
            <el-tag type="info">进度: {{ currentQuestionIndex + 1 }} / {{ questions.length }}</el-tag>
          </div>
        </div>
      </template>

      <div v-if="questions.length > 0">
        <div v-if="!quizCompleted" class="question-section">
          <el-card class="question-card">
            <div class="question-content">
              <h3>单词: {{ currentQuestion.word }}</h3>
              <p v-if="currentQuestion.phonetic">音标: {{ currentQuestion.phonetic }}</p>
            </div>

            <div class="options-section">
              <el-radio-group v-model="selectedAnswer" class="options-group">
                <el-radio
                  v-for="(option, index) in currentQuestion.options"
                  :key="index"
                  :label="option"
                  class="option-item"
                  border
                >
                  {{ option }}
                </el-radio>
              </el-radio-group>
            </div>

            <div class="action-section">
              <el-button type="primary" @click="submitAnswer" :disabled="!selectedAnswer">
                {{ currentQuestionIndex === questions.length - 1 ? '完成' : '下一题' }}
              </el-button>
            </div>
          </el-card>
        </div>

        <div v-else class="results-section">
          <el-card class="results-card">
            <h2>练习完成!</h2>
            <div class="score-section">
              <p>得分: {{ score }} / {{ questions.length }}</p>
              <p>正确率: {{ Math.round((score / questions.length) * 100) }}%</p>
            </div>

            <div class="detailed-results">
              <h3>详细结果</h3>
              <el-table :data="questions" style="width: 100%">
                <el-table-column prop="word" label="单词" />
                <el-table-column label="你的答案">
                  <template #default="scope">
                    <span :class="{ 'wrong-answer': !scope.row.correct }">
                      {{ scope.row.userAnswer || '未作答' }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column prop="correctAnswer" label="正确答案" />
                <el-table-column label="状态">
                  <template #default="scope">
                    <el-tag :type="scope.row.correct ? 'success' : 'danger'">
                      {{ scope.row.correct ? '正确' : '错误' }}
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table>
            </div>

            <div class="action-section">
              <el-button type="primary" @click="restartQuiz">重新开始</el-button>
            </div>
          </el-card>
        </div>
      </div>

      <div v-else class="no-questions">
        <el-alert title="暂无练习题目" type="info" description="请先标记一些单词为未掌握，然后进行练习" show-icon />
        <div class="action-section" style="margin-top: 20px">
          <el-button type="primary" @click="generateQuestions">生成练习题</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'VocabularyPractice',
  data() {
    return {
      questions: [],
      currentQuestionIndex: 0,
      selectedAnswer: '',
      quizCompleted: false,
      score: 0,
    };
  },
  computed: {
    currentQuestion() {
      return this.questions[this.currentQuestionIndex] || {};
    },
  },
  methods: {
    async generateQuestions() {
      try {
        // Check if electronAPI is available
        if (typeof window.electronAPI !== 'undefined' && window.electronAPI.getWords) {
          // Fetch unknown words from the backend (words marked as not known)
          const response = await window.electronAPI.getWords({
            limit: 10,
            offset: 0,
          });

          if (response.success) {
            // Process the words into question format
            this.questions = response.data
              .filter(word => word.ok === 'NO') // Only unknown words
              .slice(0, 10) // Limit to 10 questions
              .map(word => {
                // Generate random options including the correct answer
                const options = [word.trans];
                while (options.length < 4) {
                  // In a real implementation, we would fetch more words for options
                  // For now, we'll just add some mock options
                  const mockOptions = ['随机选项1', '随机选项2', '随机选项3', '随机选项4'];
                  const randomOption = mockOptions[Math.floor(Math.random() * mockOptions.length)];
                  if (!options.includes(randomOption)) {
                    options.push(randomOption);
                  }
                }

                // Shuffle options
                for (let i = options.length - 1; i > 0; i--) {
                  const j = Math.floor(Math.random() * (i + 1));
                  [options[i], options[j]] = [options[j], options[i]];
                }

                return {
                  word: word.word,
                  phonetic: word.phonetic || '',
                  correctAnswer: word.trans,
                  options: options,
                  userAnswer: '',
                  correct: false,
                };
              });
          } else {
            throw new Error(response.error || 'Failed to load practice questions');
          }
        } else {
          console.warn('Electron API not available, running in browser development mode');
          // For development, use mock data
          this.questions = [
            {
              word: 'abandon',
              phonetic: '[əˈbændən]',
              correctAnswer: '放弃',
              options: ['继续', '放弃', '开始', '结束'],
              userAnswer: '',
              correct: false,
            },
            {
              word: 'ability',
              phonetic: '[əˈbɪləti]',
              correctAnswer: '能力',
              options: ['责任', '能力', '机会', '问题'],
              userAnswer: '',
              correct: false,
            },
            {
              word: 'academic',
              phonetic: '[ˌækəˈdemɪk]',
              correctAnswer: '学术的',
              options: ['实践的', '学术的', '商业的', '娱乐的'],
              userAnswer: '',
              correct: false,
            },
            {
              word: 'access',
              phonetic: '[ˈækses]',
              correctAnswer: '进入，通道',
              options: ['出口', '进入，通道', '阻碍', '方法'],
              userAnswer: '',
              correct: false,
            },
          ];
        }

        this.currentQuestionIndex = 0;
        this.showResult = false;
        this.$message.success('练习题目已生成');
      } catch (err) {
        console.error('Error generating practice questions:', err);
        this.$message.error('生成练习题目失败: ' + err.message);
      }
    },

    submitAnswer() {
      if (!this.selectedAnswer) return;

      // Record user answer
      this.questions[this.currentQuestionIndex].userAnswer = this.selectedAnswer;
      this.questions[this.currentQuestionIndex].correct = this.selectedAnswer === this.currentQuestion.correctAnswer;

      // Update score if correct
      if (this.questions[this.currentQuestionIndex].correct) {
        this.score++;
      }

      // Move to next question or finish quiz
      if (this.currentQuestionIndex < this.questions.length - 1) {
        this.currentQuestionIndex++;
        this.selectedAnswer = '';
      } else {
        this.quizCompleted = true;
      }
    },

    restartQuiz() {
      this.generateQuestions();
    },
  },
};
</script>

<style scoped>
.vocabulary-practice {
  max-width: 800px;
  margin: 0 auto;
}

.practice-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.question-section {
  padding: 20px 0;
}

.question-card {
  margin-bottom: 20px;
}

.question-content h3 {
  margin-top: 0;
  color: #333;
}

.options-section {
  margin: 20px 0;
}

.options-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.option-item {
  margin-right: 0;
  padding: 10px;
  border-radius: 4px;
}

.action-section {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.results-section {
  padding: 20px 0;
}

.results-card h2 {
  text-align: center;
  color: #333;
  margin-top: 0;
}

.score-section {
  text-align: center;
  margin: 20px 0;
  font-size: 18px;
}

.detailed-results {
  margin: 30px 0;
}

.wrong-answer {
  color: #f56c6c;
  text-decoration: line-through;
}

.no-questions {
  text-align: center;
  padding: 40px 0;
}
</style>
